package ru.incoremedia.gwttest.application.server.controller;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.rpcforms.server.annotation.FormController;
import com.google.gwt.rpcforms.server.controller.ProcessSubmitController;
import ru.incoremedia.gaeutils.action.TransactionalAction;
import ru.incoremedia.gwttest.application.client.dto.AuthInfo;
import ru.incoremedia.gwttest.application.client.dto.UserInfoDto;
import ru.incoremedia.gwttest.application.server.model.UserInfo;
import ru.incoremedia.gwttest.application.client.action.GetAuthInfoAction;
import ru.incoremedia.gwttest.application.server.dao.UserInfoDao;
import ru.incoremedia.gwttest.core.client.security.UserRole;
import ru.incoremedia.gwttest.core.server.context.RequestContext;
import ru.incoremedia.gwttest.core.server.util.DtoUtils;


@FormController(GetAuthInfoAction.AUTH_INFO_CONTROLLER)
public class AuthInfoController implements ProcessSubmitController<AuthInfo> {

    @Override
    public AuthInfo processSubmit() {
        
        final AuthInfo authInfo = new AuthInfo();
        final UserService userService = UserServiceFactory.getUserService();

        authInfo.setLoginUrl(userService.createLoginURL("/"));
        authInfo.setLogoutUrl(userService.createLogoutURL("/"));
        UserRole userRole = RequestContext.getInstance().getUserRole();
        authInfo.setUserRole(userRole);
        
        if(userRole != UserRole.ROLE_GUEST) {
            new TransactionalAction<Void>() {
                @Override
                public Void doInTransaction() {
                    UserInfo savedInfo = new UserInfoDao().get(userService.getCurrentUser().getUserId());
                    
                    if(savedInfo == null) {                                            
                        savedInfo = new UserInfo(userService.getCurrentUser().getUserId());
                    }
                    
                    savedInfo.setProperty(UserInfo.Property.EMAIL, userService.getCurrentUser().getEmail());
                    savedInfo.setProperty(UserInfo.Property.NICKNAME, userService.getCurrentUser().getNickname());

                    UserInfoDto userInfoDto = new UserInfoDto();
                    DtoUtils.copyProperties(savedInfo, userInfoDto);
                    authInfo.setUserInfoDto(userInfoDto);

                    new UserInfoDao().saveOrUpdate(savedInfo);
                    return null;
                }
            }.execute();
        }

        return authInfo;
    }
}
